#pragma once

#include <iostream>
#include <string>
#include <pthread.h>

namespace MyThread
{
    typedef void (*func_t)(const std::string &name);
    class Thread
    {
    public:
        Thread(const std::string &name, func_t func) : _name(name), _func(func)
        {
        }
        void Excute()
        {
            _isrunning = true;
            _func(_name);
            _isrunning = false;
        }
        static void *ThreaRoutine(void *args)
        {
            Thread *self = static_cast<Thread *>(args);
            self->Excute();
            return (void*)123;
        }
        bool start()
        {
            std::cout << _name << " is start" << std::endl;
            if (0 == pthread_create(&_tid, nullptr, ThreaRoutine, this))
                return true;
            return false;
        }
        void stop()
        {
            if (_isrunning)
            {
                pthread_cancel(_tid);
                _isrunning = false;
                std::cout << _name << " is stop" << std::endl;
            }
        }
        void join()
        {
            if (!_isrunning)
            {
                void* ret = nullptr;
                int n = pthread_join(_tid, &ret);
                if(n == 0)
                std::cout << _name << " is join, return val:"<< (uint64_t)ret << std::endl;
            }
        }
        ~Thread()
        {
            // stop();
            // join();
        }

    private:
        const std::string _name;
        pthread_t _tid;
        bool _isrunning;
        func_t _func;
    };

}